package org.zhenglide.oa.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.zhenglide.oa.entity.Employee;
import org.zhenglide.oa.entity.LeaveBill;
import org.zhenglide.oa.service.ILeaveBillService;
import org.zhenglide.oa.service.ITaskService;



@Controller
@RequestMapping("/task")
public class TaskController {
	
	@Autowired
	ITaskService myTaskService;
	 @Autowired
	 TaskService taskService;
	 @Autowired
	 RuntimeService runtimeService;
	@Autowired
	ILeaveBillService leaveBillService;
	
	@Autowired
	HistoryService historyService;
	@Autowired
	RepositoryService repositoryService;
    @RequestMapping("taskList")
    public String taskList(HttpServletRequest req){
    	Employee employee= (Employee)req.getSession().getAttribute("employee");
    	System.out.println(employee.getName());
    	List<Task> taskList = myTaskService.getTaskListByName(employee.getName());
    	
    	
    	req.setAttribute("taskList", taskList);
    	return "workflow/task";
    }
    
    @RequestMapping("startProcess")
    public String startProcess(Integer id,HttpServletRequest req){
    	LeaveBill leaveBill = leaveBillService.getById(id);
    	//设置状态为审核中
    	leaveBill.setState(1);
    	leaveBillService.updateById(leaveBill);
    	
    	Employee employee= (Employee)req.getSession().getAttribute("employee");
    	
    	
    	String key = leaveBill.getClass().getSimpleName();
    	
    	Map<String,Object> variables= new HashMap<String,Object>();
    	variables.put("inputUser", employee.getName());
    	String objId = key+"."+id;
		variables.put("objId", objId);
    	ProcessInstance pi = runtimeService.startProcessInstanceByKey(key,objId,variables);
    	
    	
    	
    	return "redirect:/leaveBill/list";
    }
    
    @RequestMapping("viewTaskForm")
    public String viewTaskForm(Integer taskId,HttpServletRequest req){
    	
    	Task task = taskService.createTaskQuery().taskId(taskId.toString()).singleResult();
    	
    	ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
    	
    	
    	String objId = pi.getBusinessKey();
    	
    	String id = objId.split("\\.")[1];
    	
    	LeaveBill leaveBill = leaveBillService.getById(id);
    	
    	req.setAttribute("leaveBill", leaveBill);
    	
    	List<Comment> processInstanceComments = taskService.getProcessInstanceComments(pi.getId());
    	
    	req.setAttribute("conmentList", processInstanceComments);
    	
    	BpmnModel bpmnModel = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
    	Process process = bpmnModel.getProcesses().get(bpmnModel.getProcesses().size()-1);
    	
    	Collection<FlowElement> flowElements = process.getFlowElements();
    	ArrayList<String> outcomeList = new ArrayList<String>();
    	for (FlowElement flowElement : flowElements) {
    		if (flowElement instanceof UserTask) {
    			UserTask userTask=(UserTask) flowElement;
    			//获取入线信息
    			List<SequenceFlow> incomingFlows = userTask.getIncomingFlows();
    			for (SequenceFlow sequenceFlow : incomingFlows) {
    				if(StringUtils.isNoneBlank(sequenceFlow.getName())){
    					outcomeList.add(sequenceFlow.getName());
    				}
    			}
    			}
		}
    	outcomeList.add("默认提交");
    	req.setAttribute("outcomeList", outcomeList);
    	req.setAttribute("taskId", taskId);
    	return "workflow/taskForm";
    }
    
    /**
	 * 提交任务
	 */
    @RequestMapping("submitTask")
	public String submitTask(String taskId ,String comment ,String outcome,String id,HttpServletRequest req){
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
    	Employee employee= (Employee)req.getSession().getAttribute("employee");

		//由于流程用户上下文对象是线程独立的，所以要在需要的位置设置，要保证设置和获取操作在同一个线程中
        Authentication.setAuthenticatedUserId(employee.getName());//批注人的名称  一定要写，不然查看的时候不知道人物信息
		
        
		taskService.addComment(taskId, task.getProcessInstanceId(), comment);
		
		Map<String, Object> variables = new HashMap<String,Object>();
		if(outcome!=null && !outcome.equals("默认提交")){
			variables.put("outcome", outcome);
		}
		taskService.complete(taskId, variables);
	    ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
    	
	    if(pi == null){
	    	 LeaveBill leaveBill = leaveBillService.getById(id);
	     	//设置状态为审核中
	     	leaveBill.setState(2);
	     	leaveBillService.updateById(leaveBill); 
	    }
	   
		return "redirect:/task/taskList";
	}
    
    @RequestMapping("viewHisComment")
    public String viewHisComment(String id,HttpServletRequest req){
   
    	
    	
    	
    	
    	LeaveBill leaveBill = leaveBillService.getById(id);
    	String objId = leaveBill.getClass().getSimpleName()+"."+id;
    	//流程结束，流程实例为空，要通过历史流程实例查询
//    	ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(objId).singleResult();
    	HistoricProcessInstance pi = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(objId).singleResult();
    	
    	/**2:使用历史的流程变量查询，返回历史的流程变量的对象，获取流程实例ID*/
//		HistoricVariableInstance hvi = historyService.createHistoricVariableInstanceQuery()//对应历史的流程变量表
//						.variableValueEquals("objId", objId)//使用流程变量的名称和流程变量的值查询
//						.singleResult();
    	req.setAttribute("leaveBill", leaveBill);
    	System.out.println(objId);
    	List<Comment> processInstanceComments = taskService.getProcessInstanceComments(pi.getId());
    	
    	req.setAttribute("commentList", processInstanceComments);
    	 return "workflow/taskFormHis";
    }
}
